<template>
  <div class="m-import-data">
    <el-button plain @click="showDialog">
      <img src="@/assets/svg/excel.svg" />
      批量导入
    </el-button>

    <el-dialog
      title="批量导入"
      width="40%"
      v-model="dialogVisible"
      :beforeClose="beforeClose"
    >
      <el-button
        v-if="props.download"
        class="m-import-data__download-btn"
        :loading="downloadLoading"
        @click="downloadTemplate"
        >下载模版</el-button
      >
      <MUpload
        v-if="!percentage && !resMessage"
        drag
        :limit="1"
        v-bind="$attrs"
        :http="uploadHttp"
        :showMessage="false"
      >
        <slot>点击或拖拽上传模版文件</slot>
      </MUpload>

      <!-- 进度条 -->
      <el-progress v-else-if="!resMessage" :percentage="percentage" />

      <!-- 导入结果 -->
      <div v-else class="m-import-data__res">
        {{ resMessage }}
        <a v-if="resErrorUrl" @click="downResErrorUrl">下载错误信息</a>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { DialogBeforeCloseFn } from 'element-plus'
import { ref } from 'vue'
import { useProgressFake } from '@/hooks'
import { importDataProps, importDataEmits } from './importData'
import { useDownloadTemplate } from './hooks/useDownloadTemplate'
import { MUpload } from '@/components/upload'

defineOptions({
  name: 'MImportData'
})

const props = defineProps(importDataProps)
const emit = defineEmits(importDataEmits)

const { downloadLoading, downloadTemplate } = useDownloadTemplate(props)

const dialogVisible = ref(false)
const showDialog = () => {
  dialogVisible.value = true
}

// 导入
let percentageCancel = () => {}
const percentage = ref(0)
const resMessage = ref('')
const resErrorUrl = ref<Nullable<string>>(null)

const beforeClose: DialogBeforeCloseFn = (done) => {
  percentageCancel()
  percentage.value = 0
  resMessage.value = ''
  resErrorUrl.value = null
  done()
}

const uploadHttp = (formData: FormData): Promise<any> => {
  // 进度条
  const { cancel } = useProgressFake(
    (percent) => {
      percentage.value = percent
    },
    {
      startNum: 1,
      interval: 100,
      maxNum: 99,
      increaseNum: 3
    }
  )
  percentageCancel = cancel

  return props
    .http(formData)
    .then((res) => {
      resMessage.value = res.message || '导入结束！导入成功'
      resErrorUrl.value = res.errorUrl || null
      emit('reload')
    })
    .catch((err) => {
      resMessage.value = err.message || '导入结束！导入失败'
      resErrorUrl.value = err.errorUrl || null
    })
    .finally(() => {
      percentage.value = 0
    })
}

// 下载错误信息
const downResErrorUrl = () => {
  if (!resErrorUrl.value) return
  window.open(resErrorUrl.value)
}
</script>

<style lang="scss" scoped>
.m-import-data {
  img {
    margin-right: 5px;
  }
  &__download-btn {
    width: 100%;
    margin-bottom: 15px;
    :deep(.el-icon.is-loading svg) {
      color: #000000;
    }
  }
  &__res {
    text-align: center;
  }
}
</style>
